package com.iwayin.web.common;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapper;
import freemarker.template.Template;
import freemarker.template.TemplateExceptionHandler;

public class FreeMarkerManager {
	private static Configuration cfg = new Configuration();

	static {
		URL url = EmailSender.class.getClassLoader().getResource("template");
		File file = new File(url.getFile());
		try {
			cfg.setDirectoryForTemplateLoading(file);
		} catch (IOException e) {
			e.printStackTrace();
		}
		// 设置对象的包装器
		cfg.setObjectWrapper(new DefaultObjectWrapper());

		// 设置异常处理器
		// 这样的话就可以${a.b.c.d}即使没有属性也不会出错
		cfg.setTemplateExceptionHandler(TemplateExceptionHandler.IGNORE_HANDLER);
	}

	public static Template getTemplate(String templateName) {
		try {
			return cfg.getTemplate(templateName);
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}

	public static String process(Template template, Object model) {
		try {
			return org.springframework.ui.freemarker.FreeMarkerTemplateUtils
					.processTemplateIntoString(template, model);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	public static String process(String templateName, Object model) {
		return process(getTemplate(templateName), model);
	}

	public static Configuration getConfiguration() {
		return cfg;
	}
}
